package com.wlcj.www.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.IocBean;

import com.jfinal.plugin.activerecord.Db;
import com.wlcj.util.RedisUtil;
import com.wlcj.util.SqlUtil;
import com.wlcj.www.enumtype.EventTypeEnum;
import com.wlcj.www.model.data.Data;
import com.wlcj.www.model.data.DateIndustry;
import com.wlcj.www.model.data.PlatformAttention;
import com.wlcj.www.model.data.PlatformQuestion;
import com.wlcj.www.model.data.Province;
import com.wlcj.www.model.data.ProvinceIndustry;
import com.wlcj.www.model.platform.Platform;
import com.wlcj.www.util.DataUtil;
import com.wlcj.www.util.Lang;

@IocBean
public class DataService {

	// <a href="javascript:;" text="19">广东</a>
	// <a href="javascript:;" text="2">北京</a>
	// <a href="javascript:;" text="10">上海</a>
	// <a href="javascript:;" text="12">浙江</a>
	// <a href="javascript:;" text="11">江苏</a>
	// <a href="javascript:;" text="3">山东</a>
	// <a href="javascript:;" text="23">四川</a>
	// <a href="javascript:;" text="17">湖北</a>
	static List<String> commonProvinceList = Arrays.asList(new String[] { "19",
			"2", "10", "12", "11", "3", "23", "17" });

	public List<Data> getDataList(String time, String orderby, String provinceId) {
		List<Data> dataList = Data.dao.getDataList(time, orderby);
		List<Data> copyList = new ArrayList<Data>();
		for (Data d : dataList) {
			Integer platformId = d.getInt("platform_id");
			Platform pf = Platform.dao.getCachePlatformById(platformId);
			d.put("platform_name", pf.getStr("platform_name"));
			BigDecimal volume = d.getBigDecimal("volume");
			d.put("volume_display", Lang.formatMoney(volume));
			d.put("compound_interest_display",
					Lang.formatMoney(d.getDouble("compound_interest")));
			d.put("average_loan_time_display",
					Lang.formatMoney(d.getDouble("average_loan_time")));
			BigDecimal avInvestAmount = d.getBigDecimal("av_investment_amount");
			d.put("av_investment_amount_display",
					Lang.formatMoney(avInvestAmount));
			BigDecimal avBorroAmount = d.getBigDecimal("av_borrow_amount");
			d.put("av_borrow_amount_display", Lang.formatMoney(avBorroAmount));
			d.put("collecting_10_display",
					Lang.formatMoney(d.getDouble("10_collecting")));
			d.put("borrowers_10_display",
					Lang.formatMoney(d.getDouble("10_borrowers")));
			BigDecimal timeWeightVolume = d
					.getBigDecimal("time_weighted_volume");
			d.put("time_weighted_volume_display",
					Lang.formatMoney(timeWeightVolume));
			d.put("full_biaoyong_time_display",
					DataUtil.formatSecondStr(d.getDouble("full_biaoyong_time")));
			d.put("operating_time_display",
					DataUtil.formatMonthStr(d.getInt("operating_time")));
			BigDecimal registerCapital = d.getBigDecimal("registered_capital");
			d.put("registered_capital_display",
					Lang.formatMoney(registerCapital));
			d.put("leverage_display", Lang.formatMoney(d.getDouble("leverage")));
			BigDecimal inflow30 = d.getBigDecimal("30_inflows");
			d.put("inflows_30_display", Lang.formatMoney(inflow30));
			BigDecimal still60 = d.getBigDecimal("60_still");
			d.put("still_60_display", Lang.formatMoney(still60));
			BigDecimal cumulativeAmount = d.getBigDecimal("cumulative_amount");
			d.put("cumulative_amount_display",
					Lang.formatMoney(cumulativeAmount));

			if (StringUtils.isNotBlank(provinceId)) {
				String pid = pf.getInt("province_id") + "";
				boolean flag1 = provinceId.equals("other")
						&& !commonProvinceList.contains(pid);
				boolean flag2 = provinceId.equals(pid);
				if (flag1 || flag2)
					copyList.add(d);
			}
		}
		if (StringUtils.isBlank(provinceId))
			return dataList;
		else
			return copyList;
	}

	public List<ProvinceIndustry> getProvinceIndustry(String startTime,
			String endTime, String orderby) {
		List<ProvinceIndustry> list = ProvinceIndustry.dao.getProvinceIndustry(
				startTime, endTime, orderby);
		for (ProvinceIndustry pi : list) {
			Province p = Province.dao.getCacheProvinceById(pi
					.getInt("province_id"));
			pi.put("province_name",
					p == null ? "全国" : p.getStr("provinces_name"));
			BigDecimal volume = pi.getBigDecimal("volume");
			pi.put("volume_display", Lang.formatMoney(volume));
			pi.put("volume_month_growth_display",
					pi.getDouble("volume_month_growth").intValue());
			pi.put("platform_month_growth2_display",
					pi.getDouble("platform_month_growth2").intValue());
			BigDecimal loanBalance = pi.getBigDecimal("loan_balance");
			pi.put("loan_balance_display", Lang.formatMoney(loanBalance));
			pi.put("compound_interest_display",
					Lang.formatMoney(pi.getDouble("compound_interest")));
			pi.put("average_loan_time_display",
					Lang.formatMoney(pi.getDouble("average_loan_time")));
			BigDecimal tempNum = new BigDecimal(10000d);
			BigDecimal investNum = new BigDecimal(
					pi.getDouble("month_investment_num")).divide(tempNum);
			BigDecimal borrowNum = new BigDecimal(
					pi.getDouble("month_borrow_num")).divide(tempNum);
			pi.put("month_investment_num_display", Lang.formatMoney(investNum));
			pi.put("month_borrow_num_display", Lang.formatMoney(borrowNum));
		}
		return list;
	}

	public List<DateIndustry> getDateIndustry() {
		List<DateIndustry> list = DateIndustry.dao.getDateIndustry();
		for (DateIndustry di : list) {
			BigDecimal volume = di.getBigDecimal("volume");
			di.put("volume_display", Lang.formatMoney(volume));
			BigDecimal loanBalance = di.getBigDecimal("loan_balance");
			di.put("loan_balance_display", Lang.formatMoney(loanBalance));
			di.put("compound_interest_display",
					Lang.formatMoney(di.getDouble("compound_interest")));
			di.put("average_loan_time_display",
					Lang.formatMoney(di.getDouble("average_loan_time")));
			BigDecimal tempNum = new BigDecimal(10000d);
			BigDecimal investNum = new BigDecimal(
					di.getDouble("current_investment_num")).divide(tempNum);
			BigDecimal borrowNum = new BigDecimal(
					di.getDouble("current_borrow_num")).divide(tempNum);
			di.put("current_investment_num_display",
					Lang.formatMoney(investNum));
			di.put("current_borrow_num_display", Lang.formatMoney(borrowNum));
		}
		return list;
	}

	@Aop("tx")
	public void addUserAttentionPlatform(int uid, int pid) {
		// 先删后增
		String sql = "delete from wd_new_platform_attention where user_id = ? and platform_id = ?";
		Db.update(sql, uid, pid);
		PlatformAttention pa = new PlatformAttention();
		pa.set("user_id", uid);
		pa.set("platform_id", pid);
		pa.save();
	}

	public List<Province> getAllProvinces() {
		String sql = "select provinces_id from wd_d_provinces ";
		List<Province> list = Province.dao.find(sql);
		List<Province> lists = new ArrayList<Province>();
		List<ProvinceIndustry> provinceList = ProvinceIndustry.dao
				.getProvince();
		for (Province p : list) {
			for (int i = 0; i < provinceList.size(); i++) {
				if (provinceList.get(i).get("province_id")
						.equals(p.getInt("provinces_id"))) {
					p.setAttrs(Province.dao.getCacheProvinceById(p
							.getInt("provinces_id")));
					lists.add(p);
				}
			}
		}
		return lists;
	}

	public List<Province> getProvincesByName(String name) {
		String sql = "select provinces_id from wd_d_provinces w where provinces_name like '%"
				+ name + "%'";
		List<Province> list = Province.dao.find(sql);
		return list;
	}

	public List<PlatformQuestion> getQuestion(Map<String, Object> entity) {
		String time = null;// entity.get("time");
		Integer area = null;// entity.get("area");
		Integer type = null;// entity.get("type");
		if (entity.get("time").toString().contains("问题时间")) {
			time = null;
		} else {
			time = DataUtil.toTime(entity.get("time").toString());
		}
		// 事件类型
		if (entity.get("type").toString().contains("事件类型")) {
			type = null;
		} else {
			type = DataUtil.toProblem(entity.get("type").toString());
		}
		// 地区
		if (entity.get("area").toString().contains("地区")
				|| entity.get("area").toString().contains("全国")) {
			area = null;
		} else {
			List<Province> list = getProvincesByName(entity.get("area")
					.toString());
			if (list != null && list.size() > 0) {
				area = list.get(0).getInt("provinces_id");
			} else {
				area = null;
			}
		}

		String orderby = " " + entity.get("column") + " "
				+ entity.get("orderby");

		List<PlatformQuestion> list = PlatformQuestion.dao.getQuestion(time,
				area, type, orderby);
		for (PlatformQuestion pq : list) {
			pq.put("registered_capital_display",
					pq.getBigDecimal("registered_capital").compareTo(
							new BigDecimal("0")) > 0 ? Lang.formatMoney(pq
							.getBigDecimal("registered_capital")) + "万元" : "-");// 注册资金
			pq.put("collecting_amount_display",
					pq.getBigDecimal("collecting_amount").compareTo(
							new BigDecimal("0")) > 0 ? Lang.formatMoney(pq
							.getBigDecimal("collecting_amount")) + "万元" : "-");
			pq.put("num_display", pq.getInt("num") != 0 ? pq.getInt("num")
					+ "人" : "-");// 涉及人数
			pq.put("problem_type_display",
					EventTypeEnum.getEnumByName(pq.getInt("problem_type"))
							.getDesc());// 事件类型
			pq.put("online_time_display",
					DataUtil.formatTime(pq.getDate("online_time")));
			pq.put("problem_time_display",
					DataUtil.formatTime(pq.getDate("problem_time")));
		}
		return list;
	}

	public List<ProvinceIndustry> getProvinceOrderby(String litter,
			String litterTwo, String startData, String stopData) {

		return ProvinceIndustry.dao.getLittle(litter, litterTwo, startData,
				stopData);

	}

	public List<Data> getDataList(String[] time, String orderby,
			String provinceId) {

		List<Data> dataList = Data.dao.getDataList(time[0], time[1], orderby);
		List<Data> copyList = new ArrayList<Data>();
		for (Data d : dataList) {
			Integer platformId = d.getInt("platform_id");
			Platform pf = Platform.dao.getCachePlatformById(platformId);
			d.put("platform_name", pf.getStr("platform_name"));
			BigDecimal volume = d.getBigDecimal("volume");
			d.put("volume_display", Lang.formatMoney(volume));
			d.put("compound_interest_display",
					Lang.formatMoney(d.getDouble("compound_interest")));
			d.put("average_loan_time_display",
					Lang.formatMoney(d.getDouble("average_loan_time")));
			BigDecimal avInvestAmount = d.getBigDecimal("av_investment_amount");
			if (avInvestAmount == null) {
				d.put("av_investment_amount_display", new BigDecimal("0"));
			} else {
				d.put("av_investment_amount_display",
						Lang.formatMoney(avInvestAmount));
			}
			BigDecimal avBorroAmount = d.getBigDecimal("av_borrow_amount");
			if (avBorroAmount == null) {
				d.put("av_borrow_amount_display", new BigDecimal("0"));
			} else {
				d.put("av_borrow_amount_display",
						Lang.formatMoney(avBorroAmount));
			}
			d.put("collecting_10_display", Lang.formatMoney(d
					.getDouble("10_collecting") == null ? new Double("0") : d
					.getDouble("10_collecting")));
			d.put("borrowers_10_display", Lang.formatMoney(d
					.getDouble("10_borrowers") == null ? new Double("0") : d
					.getDouble("10_borrowers")));
			Double timeWeightVolume = d.getDouble("time_weighted_volume");
			d.put("time_weighted_volume_display",
					Lang.formatMoney(timeWeightVolume));
			d.put("full_biaoyong_time_display",
					DataUtil.formatSecondStr(d.getDouble("full_biaoyong_time")));
			d.put("operating_time_display", DataUtil.formatMonthStr(d
					.getInt("operating_time") == null ? 0 : d
					.getInt("operating_time")));
			BigDecimal registerCapital = d.getBigDecimal("registered_capital") == null ? new BigDecimal(
					"0") : d.getBigDecimal("registered_capital");
			d.put("registered_capital_display",
					Lang.formatMoney(registerCapital));
			d.put("leverage_display",
					Lang.formatMoney(d.getDouble("leverage") == null ? new Double(
							"0") : d.getDouble("leverage")));
			BigDecimal inflow30 = d.getBigDecimal("30_inflows") == null ? new BigDecimal(
					"0") : d.getBigDecimal("30_inflows");
			d.put("inflows_30_display", Lang.formatMoney(inflow30));
			BigDecimal still60 = d.getBigDecimal("60_still") == null ? new BigDecimal(
					"0") : d.getBigDecimal("60_still");
			d.put("still_60_display", Lang.formatMoney(still60));
			BigDecimal cumulativeAmount = d.getBigDecimal("cumulative_amount") == null ? new BigDecimal(
					"0") : d.getBigDecimal("cumulative_amount");
			d.put("cumulative_amount_display",
					Lang.formatMoney(cumulativeAmount));

			if (StringUtils.isNotBlank(provinceId)) {
				String pid = pf.getInt("province_id") + "";
				boolean flag1 = provinceId.equals("other")
						&& !commonProvinceList.contains(pid);
				boolean flag2 = provinceId.equals(pid);
				if (flag1 || flag2)
					copyList.add(d);
			}
		}
		if (StringUtils.isBlank(provinceId))
			return dataList;
		else
			return copyList;
	}

	/**
	 * 当月投资人数 and 累计投资
	 */
	public List<Data> getInvestPeople(String investTime) {
		return Data.dao.find(SqlUtil.sql("data.getInvestPeople"), investTime);
	}

	/**
	 * 累计代还
	 */
	public List<Data> getDayStill(String stillTime) {
		return Data.dao.find(SqlUtil.sql("data.getDayStill"), stillTime);
	}

	/**
	 * 投资利率分布
	 */
	public List<Data> getInvestmentInterest(String investTime) {
		return Data.dao.find(SqlUtil.sql("data.getInvestmentInterest"),
				investTime, investTime, investTime, investTime, investTime);
	}

	/**
	 * 投资期限分布
	 */
	public List<Data> getInvestmentPeriod(String investTime) {
		return Data.dao.find(SqlUtil.sql("data.getInvestmentPeriod"),
				investTime, investTime, investTime, investTime, investTime);
	}

	/**
	 * 当月行业每日成交量走势情况
	 */
	public Map<String, List<Data>> getYesterdayDataPkDayData(String investTime,
			String invest2Time, String centerMonth, String lastMonth) {
		Map<String, List<Data>> maps = new HashMap<String, List<Data>>();
		maps.put("lastMonth", Data.dao.find(
				SqlUtil.sql("data.getYesterdayDataPkDayData"), lastMonth,
				centerMonth));
		maps.put("nowMonth", Data.dao.find(
				SqlUtil.sql("data.getYesterdayDataPkDayData"), invest2Time,
				investTime));
		return maps;
	}

	/**
	 * 默认成交量前3
	 * 
	 * @param time
	 * @return
	 */
	public List<Data> topThreeOrOrther(String time, String sortField,
			Integer[] platformIdArray, Integer dayOrMonth) {
		platformIdArray = DataUtil.removeZero(platformIdArray);

		if (platformIdArray == null) {
			List<Data> topThreeId = Data.dao.find(
					SqlUtil.sql("data.getThreePid"), time, sortField);
			List<Data> data = new ArrayList<Data>();
			for (int i = 0; i < topThreeId.size(); i++) {
				String key = topThreeId.get(i).getInt("platform_id") + "-"
						+ "day";
				// System.out.println(RedisUtil.get(key));
				List<Data> d = RedisUtil.get(key);
				data.addAll(d);
			}
			return data;
		} else {
			List<Data> data = new ArrayList<Data>();
			switch (dayOrMonth) {
			case 1:
				for (int i = 0; i < platformIdArray.length; i++) {
					List<Data> d = RedisUtil.get(platformIdArray[i] + "-"
							+ "day");
					data.addAll(d);
				}
				break;
			case 2:
				for (int i = 0; i < platformIdArray.length; i++) {
					List<Data> d = new ArrayList<Data>();
					if ("volume".equals(sortField)
							|| "investment_num".equals(sortField)
							|| "borrower_num".equals(sortField)) {
						d = RedisUtil.get("sum" + "-" + platformIdArray[i]
								+ "-" + "week");
					} else if ("30_inflows".equals(sortField)
							|| "60_still".equals(sortField)
							|| "cumulative_amount".equals(sortField)) {
						d = RedisUtil.get("common" + "-" + platformIdArray[i]
								+ "-" + "week");
					} else {
						d = RedisUtil.get("avg" + "-" + platformIdArray[i]
								+ "-" + "week");
					}
					data.addAll(d);
				}
				break;
			case 3:
				for (int i = 0; i < platformIdArray.length; i++) {
					List<Data> d = new ArrayList<Data>();
					if ("volume".equals(sortField)
							|| "investment_num".equals(sortField)
							|| "borrower_num".equals(sortField)) {
						d = RedisUtil.get("sum" + "-" + platformIdArray[i]
								+ "-" + "month");
					} else if ("30_inflows".equals(sortField)
							|| "60_still".equals(sortField)
							|| "cumulative_amount".equals(sortField)) {
						d = RedisUtil.get("common" + "-" + platformIdArray[i]
								+ "-" + "month");
					} else {
						d = RedisUtil.get("avg" + "-" + platformIdArray[i]
								+ "-" + "month");
					}
					data.addAll(d);
				}
				break;
			default:
				return null;
			}
			return data;
		}
	}

	/**
	 * 每日成交排行榜
	 * 
	 * @param time
	 * @param pid
	 * @return
	 */
	public List<Platform> getVolume(String time, Integer pid) {
		List<Platform> platform = Platform.dao.getVolume(time, pid);
		for (Platform p : platform) {
			p.put("platform_name", p.getStr("platform_name"));
			p.put("volume", Lang.formatMoney(p.getBigDecimal("volume")));
		}
		return platform;
	}

	@SuppressWarnings("unused")
	public List<Data> getPids(String date) {
		return Data.dao.find(SqlUtil.sql("data.getAllPid"), date);
	}

	/**
	 * 日数据
	 * 
	 * @param minDate
	 * @param pid
	 * @return
	 */
	public List<Data> getDayData(String minDate, int pid) {
		return Data.dao.find(SqlUtil.sql("data.getDayData"), pid, minDate);
	}

	/**
	 * 周数据,月数据-sum
	 * 
	 * @param xzhou
	 * @param pid
	 * @return
	 */
	public List<Data> getSumData(List<String> xzhou, int pid) {
		List<Data> data = new ArrayList<Data>();
		for (int j = 0; j < xzhou.size(); j = j + 2) {
			List<Data> d = Data.dao.find(SqlUtil.sql("data.getSumData"), pid,
					xzhou.get(j), xzhou.get(j + 1));
			if (CollectionUtils.isEmpty(d)) {
				Data dd = new Data();
				dd.put("count", 0);
				dd.put("volume", new BigDecimal("0"));
				dd.put("investment_num", new BigDecimal("0"));
				dd.put("borrower_num", new BigDecimal("0"));
				dd.put("platform_id", pid);
				Platform pf = Platform.dao.getCachePlatformById(pid);
				dd.put("platform_name", pf.get("platform_name"));

				d.add(dd);
			}
			data.addAll(d);
		}
		return data;
	}

	/**
	 * 周数据,月数据-common
	 * 
	 * @param xzhou
	 * @param pid
	 * @return
	 */
	public List<Data> getCommonData(List<String> xzhou, int pid) {
		List<Data> data = new ArrayList<Data>();
		for (int i = 0; i < xzhou.size(); i++) // 外循环是循环的次数
		{
			for (int j = xzhou.size() - 1; j > i; j--) // 内循环是
														// 外循环一次比较的次数
			{
				if (xzhou.get(i).equals(xzhou.get(j))) {
					xzhou.remove(j);
				}
			}
		}
		Collections.sort(xzhou);
		for (int j = 0; j < xzhou.size(); j++) {
			List<Data> d = Data.dao.find(SqlUtil.sql("data.getCommonData"),
					pid, xzhou.get(j));
			if (CollectionUtils.isEmpty(d)) {
				Data dd = new Data();
				dd.put("count", 0);
				dd.put("30_inflows", new BigDecimal("0"));
				dd.put("60_still", new BigDecimal("0"));
				dd.put("cumulative_amount", new BigDecimal("0"));
				dd.put("platform_id", pid);
				Platform pf = Platform.dao.getCachePlatformById(pid);
				dd.put("platform_name", pf.get("platform_name"));

				d.add(dd);
			}
			data.addAll(d);
		}
		return data;
	}

	/**
	 * 周数据,月数据-avg
	 * 
	 * @param xzhou
	 * @param pid
	 * @return
	 */
	public List<Data> getAvgData(List<String> xzhou, int pid) {
		List<Data> data = new ArrayList<Data>();
		for (int j = 0; j < xzhou.size(); j = j + 2) {
			List<Data> d = Data.dao.find(SqlUtil.sql("data.getAvgData"), pid,
					xzhou.get(j), xzhou.get(j + 1));
			if (CollectionUtils.isEmpty(d)) {
				Data dd = new Data();
				dd.put("count", 0);
				dd.put("compound_interest", new BigDecimal("0"));
				dd.put("average_loan_time", new BigDecimal("0"));
				dd.put("platform_id", pid);
				Platform pf = Platform.dao.getCachePlatformById(pid);
				dd.put("platform_name", pf.get("platform_name"));

				d.add(dd);
			}
			data.addAll(d);
		}
		return data;
	}
}
